package org.atguigu.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class SqlSessionUtil {
    private static SqlSessionFactory sqlSessionFactory;
    static {
        //加载主配置文件mybatis。xml
        //测试mybatis
        //读取主配置文件
        InputStream is = null;
        try {
            is = Resources.getResourceAsStream("mybatis.xml");
            //取得SqlSession对象的过程
            //先创建一个SqlSession工厂构建者 对象
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            //构建者通过调用build方法，构建出来SqlSession工厂对象
             sqlSessionFactory = builder.build(is);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
    //取得SqlSession对象
    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession();
    }
    //关闭SqlSession
    public static void close(SqlSession session) {
        if (session != null) {
            session.close();
        }

    }

}
